package com.learn.controller;

import com.learn.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.jar.Attributes;

/**
 * @Author fengqq
 * @Description 用户模块--控制层
 * @Date 2024/8/16  14:07
 */
@Controller
@Slf4j
public class UserController {

    //显示login.html页面
    @GetMapping("/login.html")
    public String showLogin(HttpServletRequest request) {

        String msg = (String) request.getAttribute("msg");
        log.info(msg);
        return "login";
    }

    //处理login登录请求 admin 123
    @PostMapping("/login")
    public String handleLogin(
            String username,
            String password,
            Model model,
            HttpSession session) {
        log.info("username:{},password:{}", username, password);
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            //登录失败 用户名或密码不能为空
            model.addAttribute("errMsg", "用户名或密码不能为空");
            //跳转到登录页面login.html 回显错误消息
            return "login"; //请求转发
        }
        if ("admin".equals(username) && "123".equals(password)) {
            //在session会话中存储当前登录的信息
            session.setAttribute("username", username);
            //登录成功 跳转到main.html
            return "redirect:/main.html";//重定向 避免表单重复提交
        }
        //登录失败 用户名或者密码错误
        model.addAttribute("errMsg", "用户名或密码错误");
        //跳转到登录页面login.html 回显错误消息
        return "login";
    }

    //显示main.html
    @GetMapping("/main.html")
    public String showMain() {
        return "main";
    }

    //用户登出
    @GetMapping("/logout")
    public String handleLogOut(HttpSession session) {
        //清空session中所有数据
        session.invalidate();
        //跳转到 login.html
        return "redirect:/login.html";
    }

    @GetMapping("/basic_table.html")
    public String showBasic_table(Model model) {
        //添加users用户集合
        ArrayList<User> users = new ArrayList<>();
        Collections.addAll(users,
                new User("1", "张三", "3", "111.@qq.com"),
                new User("2", "李四", "2", "222.@qq.com"),
                new User("3", "王五", "3", "333.@qq.com"));
        model.addAttribute("users", users);


        return "basic_table";
    }
    @GetMapping("/form_layouts.html")
    public String showForm_elements() {
        return "form_layouts";
    }
}










